package net.hn.hnms.biz.safety.trinity.service;

import lombok.RequiredArgsConstructor;
import net.hn.hnms.biz.api.feign.model.DataStateVo;
import net.hn.hnms.biz.api.safety.trinity.model.RiskControlVo;

import net.hn.hnms.biz.api.safety.trinity.model.TrinityLevel;
import net.hn.hnms.biz.safety.trinity.entity.RiskRecordDto;
import net.hn.hnms.biz.safety.trinity.entity.RiskRecordVo;
import net.hn.hnms.biz.common.jpa.utils.ResponsePage;
import net.hn.hnms.biz.safety.trinity.dao.RiskControlListDao;
import net.hn.hnms.biz.safety.trinity.dao.RiskControlMeasureDao;
import net.hn.hnms.biz.safety.trinity.dao.RiskControlMeasureRecordDao;
import net.hn.hnms.biz.safety.trinity.entity.RiskControlList;
import net.hn.hnms.biz.safety.trinity.entity.RiskControlMeasureEntity;
import net.hn.hnms.biz.safety.trinity.until.Dictionaries;
import net.hn.hnms.sys.common.mybatis.core.page.PageQuery;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;


import javax.persistence.EntityManager;
import java.text.SimpleDateFormat;
import java.util.*;


/**
 * @author 智呈物联 nzw
 * @date 2022/8/4
 */
@Service
@RequiredArgsConstructor
public class RiskControlService {

    private final JdbcTemplate locationJdbcTemplate;

    RiskControlListDao riskControlListDao;

    RiskControlMeasureRecordDao riskControlMeasureRecordDao;

    EntityManager entityManager;

    RiskControlMeasureDao riskControlMeasureDao;

    @Autowired
    public void setRiskControlListDao(RiskControlListDao riskControlListDao) {
        this.riskControlListDao = riskControlListDao;
    }

    @Autowired
    public void setRiskControlMeasureRecordDao(RiskControlMeasureRecordDao riskControlMeasureRecordDao) {
        this.riskControlMeasureRecordDao = riskControlMeasureRecordDao;
    }

    @Autowired
    public void setEntityManager(EntityManager entityManager) {
        this.entityManager = entityManager;
    }

    @Autowired
    public void setRiskControlMeasureDao(RiskControlMeasureDao riskControlMeasureDao) {
        this.riskControlMeasureDao = riskControlMeasureDao;
    }

    public RiskControlVo riskControl(String mineCode){
        Dictionaries.setMineCode(mineCode);
        RiskControlVo riskControlVo = new RiskControlVo();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy");
        String dateTime = simpleDateFormat.format(new Date())+"-01-01";
        //风险总数
        riskControlVo.setRiskCount(riskControlListDao.countAll(mineCode,dateTime));
        //重大风险
        riskControlVo.setMajorRisk(riskControlListDao.countAllByRiskLevel(Dictionaries.RISK_LEVEL_MAJOR,mineCode,dateTime));
        //风险管控记录
        int controlRecords = 0;
        try{
            controlRecords = riskControlMeasureRecordDao.countAll(mineCode,dateTime);
        }catch (Exception e){

        }
        riskControlVo.setControlRecords(controlRecords);
        return riskControlVo;
    }

    public ResponsePage<RiskRecordVo> page(PageQuery pageQuery, RiskRecordDto riskRecordDto,String mineCode){
        RiskControlList riskControlList = new RiskControlList();
        List<RiskRecordVo> riskRecordVoList = new ArrayList<>();

        //查询条件赋值
        riskControlList.setRiskMajor(riskRecordDto.getMajor());
        riskControlList.setRiskClass(riskRecordDto.getType());
        riskControlList.setRiskLevel(riskRecordDto.getLevel());
        String riskLevel = riskRecordDto.getLevel();
        String riskClass = riskRecordDto.getType();
        String riskMajor = riskRecordDto.getMajor();
        String startDay = riskRecordDto.getStartDay();
        if (startDay==null){
            startDay = "";
        }

        String endDay = riskRecordDto.getEndDay();
        if (endDay==null){
            endDay = "";
        }

        String sql = "select * from risk_control_list where 1=1";
        String countSql = "select count(*) from risk_control_list where 1=1";
        String where = "";
        if (!"".equals(startDay)){
            where += "and data_time>= '"+startDay+"'";
        }else {
            if (!"".equals(endDay)){
                where += " and data_time <= '"+endDay+"'";
            }
        }
        if (riskLevel!=null&&!"".equals(riskLevel)){
            where+="and risk_level = '"+riskLevel+"' ";
        }

        if (riskClass!=null&&!"".equals(riskClass)){
            where+="and risk_class = '"+riskClass+"' ";
        }

        if (riskMajor!=null&&!"".equals(riskMajor)){
            where+="and risk_major = '"+riskMajor+"' ";
        }
        if (mineCode!=null&&!"".equals(mineCode)){
            where+="and mine_code = '"+mineCode+"' ";
        }


        Integer pageSize = pageQuery.getPageSize();
        if (pageSize==null){
            pageSize = 10;
        }
        Integer pageNum = pageQuery.getPageNum();
        if (pageNum==null||pageNum==0){
            pageNum=1;
        }

        String page = " order by data_time desc LIMIT "+pageSize+" OFFSET "+(pageNum-1)*pageSize;

        List<RiskControlList> riskControlLists = locationJdbcTemplate.query(sql+where+page, BeanPropertyRowMapper.newInstance(RiskControlList.class));
        Map<String,Object> map = locationJdbcTemplate.queryForMap(countSql+where);
        for (RiskControlList controlList : riskControlLists){
            RiskRecordVo riskRecordVo = new RiskRecordVo();

            List<RiskControlMeasureEntity> riskControlMeasureEntities = riskControlMeasureDao.findAllByRiskId(controlList.getRiskId());
            if (riskControlMeasureEntities!=null&&riskControlMeasureEntities.size()!=0){
                RiskControlMeasureEntity riskControlMeasureEntity = riskControlMeasureEntities.get(0);
                if (riskControlMeasureEntity!=null){
                    //责任人
                    riskRecordVo.setPersonName(riskControlMeasureEntity.getDutyPersonNames());
                    //管控措施
                    riskRecordVo.setControlMeasure(riskControlMeasureEntity.getControlMeasure());
                }
            }
            String riskLocationSql ="select * from risk_location where risk_location_id = '"+controlList.getRiskLocationId()+"'";
            List<Map<String,Object>> riskLocationMap = locationJdbcTemplate.queryForList(riskLocationSql);
            if (riskLocationMap!=null&&riskLocationMap.size()!=0) {
                //风险点id
                riskRecordVo.setAddr(riskLocationMap.get(0).get("risk_location_name") + "");
            }
            if (Dictionaries.GAOTOUYAOMINECODE.equals(mineCode)){
                Dictionaries.setMineCode(mineCode);
                //风险类型
                riskRecordVo.setType(getRiskTypeName(controlList.getRiskClass()));
                //风险等级
                riskRecordVo.setLevel(getRiskLevelName(controlList.getRiskLevel()));
            }else {
                //风险类型
                riskRecordVo.setType(controlList.getRiskClass());
                //风险等级
                riskRecordVo.setLevel(controlList.getRiskLevel());
            }
            //风险描述
            riskRecordVo.setRiskDescription(controlList.getRiskDescription());
            int record = 0;
            //管控记录数量
            try {
                record = riskControlMeasureRecordDao.countByRiskId(controlList.getRiskId(), mineCode);
            }catch (Exception e){

            }
            //数据时间
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date dateTime = controlList.getDataTime();
            if (dateTime!=null){
                riskRecordVo.setDateTime(simpleDateFormat.format(dateTime));
            }
            riskRecordVo.setRecord(record);


            riskRecordVoList.add(riskRecordVo);
        }
        ResponsePage<RiskRecordVo> riskRecordVoResponsePage = new ResponsePage<RiskRecordVo>(riskRecordVoList,Integer.parseInt(map.get("count")+""));
        return riskRecordVoResponsePage;
    }

    public String getRiskTypeName(String type){
        switch (type){
            case "1":
                return "火灾";
            case "2":
                return "水灾";
            case "3":
                return "瓦斯爆炸";
            case "4":
                return "煤尘爆炸";
            case "5":
                return "顶板";
            case "6":
                return "运输系统";
        }
       return "";
    }

    public String getRiskLevelName(String riskLevel){
        if (Dictionaries.RISK_LEVEL_MAJOR.equals(riskLevel)){
            return "重大风险";
        }else if (Dictionaries.RISK_LEVEL_HIGHER.equals(riskLevel)){
            return "高风险";
        } else if (Dictionaries.RISK_LEVEL_GENERAL.equals(riskLevel)){
            return "一般风险";
        }else if (Dictionaries.RISK_LEVEL_LOW.equals(riskLevel)){
            return "低风险";
        }
        return "";
    }

    //风险分析
    public Map<String,Object> riskInfoList(String mineCode){
        Dictionaries.setMineCode(mineCode);
        Map<String,Object> map = new HashMap<>();
        List<Map<String,Object>> riskControlLists = riskControlListDao.queryAll(mineCode);
        List<Map<String,Object>> majorList = new ArrayList<>();
        List<Map<String,Object>> normalAList = new ArrayList<>();
        List<Map<String,Object>> normalBList = new ArrayList<>();
        List<Map<String,Object>> normalCList = new ArrayList<>();

        String major = Dictionaries.RISK_LEVEL_MAJOR;
        String higher = Dictionaries.RISK_LEVEL_HIGHER;
        String general = Dictionaries.RISK_LEVEL_GENERAL;
        String low = Dictionaries.RISK_LEVEL_LOW;
        for(Map<String,Object> riskControlList:riskControlLists){
            String riskLevel = riskControlList.get("riskLevel")+"";
            if (major.equals(riskLevel)){
                majorList.add(riskControlList);
                continue;
            }else if (higher.equals(riskLevel)){
                normalAList.add(riskControlList);
                continue;
            }else if (general.equals(riskLevel)){
                normalBList.add(riskControlList);
                continue;
            }else if (low.equals(riskLevel)){
                normalCList.add(riskControlList);
                continue;
            }
        }
        map.put("majorList", majorList);
        map.put("majorName", "重大风险");
        map.put("normalAList", normalAList);
        map.put("normalAName", "较大风险");
        map.put("normalBList", normalBList);
        map.put("normalBName", "一般风险");
        map.put("normalCList", normalCList);
        map.put("normalCName", "低风险");

        return map;
    }

    public void riskLevelNum(TrinityLevel trinityLevel,String mineCode){
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy");
        String dateTime = simpleDateFormat.format(new Date())+"-01-01";
        Dictionaries.setMineCode(mineCode);
        //重大风险
        trinityLevel.setSignificantRisk(riskControlListDao.countAllByRiskLevel(Dictionaries.RISK_LEVEL_MAJOR,mineCode,dateTime));
        //较大风险（二级）
        trinityLevel.setGreaterRisk(riskControlListDao.countAllByRiskLevel(Dictionaries.RISK_LEVEL_HIGHER,mineCode,dateTime));
        //一般风险（三级）
        trinityLevel.setGeneralRisk(riskControlListDao.countAllByRiskLevel(Dictionaries.RISK_LEVEL_GENERAL,mineCode,dateTime));
        //低风险（四级）
        trinityLevel.setLowRisk(riskControlListDao.countAllByRiskLevel(Dictionaries.RISK_LEVEL_LOW,mineCode,dateTime));
    }
    public List<DataStateVo> getMaxTime(String mineCode, String companyCode){
        String sql="SELECT mine_code as mineCode,max(create_time) as maxTime  FROM risk_control_list where 1=1 %s %s group by mine_code";
        if(StringUtils.isNotBlank(mineCode)){
            mineCode ="and mine_code='"+mineCode+"' ";
        }else{
            mineCode="";
        }
        if(StringUtils.isNotBlank(companyCode)&&StringUtils.isBlank(mineCode)){
            companyCode ="and company_code='"+companyCode+"' ";
        }else {
            companyCode="";
        }
        List<DataStateVo> query = locationJdbcTemplate.query(String.format(sql, mineCode, companyCode), new BeanPropertyRowMapper<>(DataStateVo.class));
        return query;
    }
}
